package com.zoffy.zoffyapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zoffy.zoffyapi.commen.IdRequest;
import com.zoffy.zoffyapi.constant.UserConstant;
import com.zoffy.zoffyapi.constant.enums.InterfaceStatusEnum;
import com.zoffy.zoffyapi.model.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.zoffy.zoffyapi.exception.BusinessException;
import com.zoffy.zoffyapi.exception.ErrorCode;
import com.zoffy.zoffyapi.model.dto.interfaceInfo.InterfaceInfoAddRequest;

import com.zoffy.zoffyapi.model.vo.InterfaceInfoVo;
import com.zoffy.zoffyapi.model.vo.UserVo;
import com.zoffy.zoffyapi.service.InterfaceInfoService;
import com.zoffy.zoffyapi.mapper.InterfaceInfoMapper;
import com.zoffy.zoffyapi.service.UserService;
import com.zoffy.zoffyapicommon.model.entity.InterfaceInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
* @author zoffy
* description 针对表【interface_info(接口信息)】的数据库操作Service实现
* createDate 2023-12-05 19:04:18
*/
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
    implements InterfaceInfoService{
    @Resource
    UserService userService;

    @Override
    public long addInterfaceInfo(HttpServletRequest request, InterfaceInfoAddRequest interfaceInfoAddRequest) {
        String name = interfaceInfoAddRequest.getName();
        String description = interfaceInfoAddRequest.getDescription();
        String url = interfaceInfoAddRequest.getUrl();
        String requestParams = interfaceInfoAddRequest.getRequestParams();
        String requestHeader = interfaceInfoAddRequest.getRequestHeader();
        String responseHeader = interfaceInfoAddRequest.getResponseHeader();
        Integer status = interfaceInfoAddRequest.getStatus();
        String method = interfaceInfoAddRequest.getMethod();


        if(StringUtils.isAnyEmpty(name,url,method) || status==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数含空值");
        }
        long userId=((UserVo)request.getSession().getAttribute("loginState")).getId();

        InterfaceInfo interfaceInfo=new InterfaceInfo();
        interfaceInfo.setName(name);
        interfaceInfo.setDescription(description);
        interfaceInfo.setUrl(url);
        interfaceInfo.setRequestParams(requestParams);
        interfaceInfo.setRequestHeader(requestHeader);
        interfaceInfo.setResponseHeader(responseHeader);
        interfaceInfo.setStatus(status);
        interfaceInfo.setMethod(method);
        interfaceInfo.setUserId(userId);

        save(interfaceInfo);
        return interfaceInfo.getId();
    }
    @Override
    public boolean deleteInterfaceInfos(HttpServletRequest request,InterfaceInfoVo[] interfaceInfoVos) {
        UserVo user= userService.getCurrentUserVo(request);
        for(InterfaceInfoVo interfaceInfoVo:interfaceInfoVos){
            Map map=new HashMap<String,Object>(){{
                put("id",interfaceInfoVo.getId());
            }};
            this.removeByMap(map);
        }
        return true;
    }

    @Override
    public boolean updateInterfaceInfo(HttpServletRequest request, InterfaceInfoVo interfaceInfoVo) {
        UserVo user= userService.getCurrentUserVo(request);
        long userId=user.getId();
        InterfaceInfo origin=this.getById(interfaceInfoVo.getId());
        if (origin.getUserId()!=userId){
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR,"非法攻击");
        }
        String method = interfaceInfoVo.getMethod();
        if (!("GET".equals(method) || "POST".equals(method))){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo=new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoVo,interfaceInfo);
        this.updateById(interfaceInfo);
        return true;
    }

    /**
     *
     * @param request HttpServletRequest
     * @param idRequest 接口Id
     * @return 接口上线结果
     */
    @Override
    public boolean onlineInterface(HttpServletRequest request, IdRequest idRequest) {
        long id=idRequest.getId();
        //判断接口是否存在
        InterfaceInfo interfaceInfo = this.getById(id);
        if(interfaceInfo==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"接口不存在");
        }

        UserVo user=userService.getCurrentUserVo(request);
        //操作用户不是管理员或接口创建者
        if((!UserConstant.ADMIN_ROLE.equals(user.getUserRole()))){
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR,"权限不足");
        }
        //
        InterfaceInfo newInterface=new InterfaceInfo();
        newInterface.setId(interfaceInfo.getId());
        newInterface.setStatus(InterfaceStatusEnum.ONLINE.getValue());
        try {
            this.updateById(newInterface);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.DATABASE_ERROR,"系统错误");
        }
        return true;
    }

    @Override
    public boolean offlineInterface(HttpServletRequest request, IdRequest idRequest) {
        long id=idRequest.getId();
        //判断接口是否存在
        InterfaceInfo interfaceInfo = this.getById(id);
        if(interfaceInfo==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"接口不存在");
        }

        UserVo user=userService.getCurrentUserVo(request);
        //操作用户不是管理员或接口创建者
        if((!UserConstant.ADMIN_ROLE.equals(user.getUserRole()))){
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR,"权限不足");
        }
        //
        InterfaceInfo newInterface=new InterfaceInfo();
        newInterface.setId(interfaceInfo.getId());
        newInterface.setStatus(InterfaceStatusEnum.OFFLINE.getValue());
        try {
            this.updateById(newInterface);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.DATABASE_ERROR,"系统错误");
        }
        return true;
    }

    @Override
    public InterfaceInfoVo getInterfaceVoById(IdRequest idRequest) {
        long id= idRequest.getId();
        if(!(id>0)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = this.getById(id);
        if (interfaceInfo==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"接口不存在");
        }
        InterfaceInfoVo interfaceInfoVo = getInterfaceInfoVo(interfaceInfo);
        interfaceInfoVo.setUrl("http://47.108.236.17:9800");
        return interfaceInfoVo;
    }


    @Override
    public IPage<InterfaceInfoVo> listOnlineInterfaceInfoByPage(InterfaceInfoQueryRequest queryRequest) {
        long page= queryRequest.getPage();
        long pageSize= queryRequest.getPageSize();
        QueryWrapper<InterfaceInfo> queryWrapper=getQueryWrapper(queryRequest);
        queryWrapper.eq("status",1);
        Page<InterfaceInfo> interfaceInfoPage= this.page(new Page<>(page,pageSize),queryWrapper);
        IPage<InterfaceInfoVo> interfaceInfoVoIPage = interfaceInfoPage.convert(interfaceInfo -> {
            InterfaceInfoVo interfaceInfoVo = getInterfaceInfoVo(interfaceInfo);
            interfaceInfoVo.setUrl("http://47.108.236.17:9800");
            return interfaceInfoVo;
        });
        return interfaceInfoVoIPage;
    }

    @Override
    public IPage<InterfaceInfoVo> listAllInterfaceInfoByPage(InterfaceInfoQueryRequest queryRequest) {
        long page= queryRequest.getPage();
        long pageSize= queryRequest.getPageSize();
        QueryWrapper<InterfaceInfo> queryWrapper=getQueryWrapper(queryRequest);
        Page<InterfaceInfo> interfaceInfoPage= this.page(new Page<>(page,pageSize),queryWrapper);
        IPage<InterfaceInfoVo> interfaceInfoVoIPage = interfaceInfoPage.convert(interfaceInfo -> {
            InterfaceInfoVo interfaceInfoVo = getInterfaceInfoVo(interfaceInfo);
            return interfaceInfoVo;
        });
        return interfaceInfoVoIPage;
    }

    private QueryWrapper<InterfaceInfo> getQueryWrapper(InterfaceInfoQueryRequest queryRequest){
        QueryWrapper<InterfaceInfo> queryWrapper=new QueryWrapper<>();
        if(queryRequest==null){
            return queryWrapper;
        }
        Long id = queryRequest.getId();
        String name = queryRequest.getName();
//        String url = queryRequest.getUrl();
//        Integer status = queryRequest.getStatus();
//        String method = queryRequest.getMethod();
//        Long userId = queryRequest.getUserId();
        String sortedField = queryRequest.getSortedField();
        String sortedOrder = queryRequest.getSortedOrder();

        if (null!=id){
            queryWrapper.eq(id>0,"id",id);
        }
        queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
//        queryWrapper.eq(StringUtils.isNotBlank(url),"url",url);
//        if(status!=null){
//            queryWrapper.eq(status>=0,"status",status);
//        }
//        queryWrapper.eq(StringUtils.isNotBlank(method),"method",method);
//        if(userId!=null){
//            queryWrapper.eq(userId>0,"user_id",userId);
//        }
        queryWrapper.orderBy(StringUtils.isNotBlank(sortedField),"asc".equals(sortedOrder),sortedField);

        return queryWrapper;
    }
    public InterfaceInfoVo getInterfaceInfoVo(InterfaceInfo interfaceInfo){
        Long id = interfaceInfo.getId();
        String name = interfaceInfo.getName();
        String description = interfaceInfo.getDescription();
        String url = interfaceInfo.getUrl();
        String requestParams = interfaceInfo.getRequestParams();
        String requestHeader = interfaceInfo.getRequestHeader();
        String responseHeader = interfaceInfo.getResponseHeader();
        Integer status = interfaceInfo.getStatus();
        String method = interfaceInfo.getMethod();


        InterfaceInfoVo interfaceInfoVo=new InterfaceInfoVo();
        interfaceInfoVo.setId(id);
        interfaceInfoVo.setName(name);
        interfaceInfoVo.setDescription(description);
        interfaceInfoVo.setUrl(url);
        interfaceInfoVo.setRequestParams(requestParams);
        interfaceInfoVo.setRequestHeader(requestHeader);
        interfaceInfoVo.setResponseHeader(responseHeader);
        interfaceInfoVo.setStatus(status);
        interfaceInfoVo.setMethod(method);

        return interfaceInfoVo;
    }
}




